package by.bsu.scs.util.form;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.upload.FormFile;
/**
 * 
 * @author Svetlana Voiteh
 * @version 1.0
 *
 * Отвечает за работу с файлами: загрузку файлов и их скачивание.
 */
public class FileManager {

	private static final Logger LOGGER = Logger
	.getLogger(FileManager.class);
	
	/**
	 * Download file
	 * 
	 * @param file
	 * @param response
	 */
	public void download(File file, HttpServletResponse response){
		/*
		 * return an application file instead of html page
		 */
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=" + file.getName());
		
    	/*
    	 * Get it from file system
    	 */
    	FileInputStream in = null;
    	ServletOutputStream out = null;
		try {
			in = new FileInputStream(file);
			
			//Get it from web path
        	//jndi:/localhost/StrutsExample/upload/superfish.zip
        	//URL url = getServlet().getServletContext().getResource("upload/superfish.zip");
        	//InputStream in = url.openStream();
        	
        	//Get it from bytes array
        	//byte[] bytes = new byte[4096];
        	//InputStream in = new ByteArrayInputStream(bytes);

        	
        	out = response.getOutputStream();
        	byte[] outputByte = new byte[1024*400];// 400kb
        	
        	/*
        	 * copy binary context to output stream
        	 */
        	while(in.read(outputByte, 0, 1024*400) != -1)
			{
				out.write(outputByte, 0, 1024*400);
			}
        	
        	        	
		} catch (FileNotFoundException e) {
			LOGGER.info("problem with download file", e.getCause());
		} catch (IOException e) {
			LOGGER.info("problem with FileInputStream or ServletOutputStream", e.getCause());
		} finally {
			try {
        		in.close();
            	out.flush();
				out.close();
			} catch (IOException e) {
				LOGGER.info("problem with close FileInputStream or ServletOutputStream", e.getCause());
			}
		}
    
	}
	
	/**
	 * Upload file
	 * 
	 * @param file
	 * @param action
	 * @return
	 */
	public String upload(FormFile file, Action action){
		FileOutputStream outputStream = null;
		FormFile formFile = file;
		String path = null;
		try {
			path = action.getServlet().getServletContext().getRealPath("")
					+ "/" + formFile.getFileName();
			try {
				outputStream = new FileOutputStream(new File(path));
				outputStream.write(formFile.getFileData());
			} catch (FileNotFoundException e) {
				LOGGER.info("problem with upload file", e.getCause());
			}
		} catch (IOException e) {
			LOGGER.info("problem with outputStream.write", e.getCause());
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					LOGGER.info("problem with outputStream.close", e.getCause());
				}
			}
		}
		
		return path;
	}
}
